<?php

namespace app\agent\controller;
use app\admin\model\Admin;
use app\common\controller\Agent;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Images;
use app\common\model\Message;
use app\common\model\Service;
use Exception;
use think\Config;
use think\Db;
use think\Env;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;
use think\Queue;


/**
 * 商家管理
 *
 * @icon fa fa-user
 */
class Shop extends Agent
{

    protected $relationSearch = true;
    protected $searchFields = 'shop_name,phone,contacts,legal_person';
    protected $multiFields = 'status';

    protected $model = null;
    protected $agent_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->assign('statusMap', \app\common\model\Shop::$statusMap);
        $this->assign('sourceMap', \app\common\model\Shop::$sourceMap);
        $this->model = new \app\common\model\Shop;
        $agent_info = session('agent');
        $this->agent_id = $agent_info['id'];
    }

    /**
 * 查看
 */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model->with(['amapProvince','amapCity','amapDistricts'])->where($where)->where('agent_id',$this->agent_id)->order($sort, $order)->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 店铺添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $images = explode(',', $params['images']);
                    $coordinate = explode(',',$params['coordinate']);
                    $params['latitude'] =$coordinate[0];
                    $params['longitude'] =$coordinate[1];
                    $params['createtime'] =time();
                    $params['updatetime'] =time();
                    $params['agent_id'] = $this->agent_id;
                    $params['service'] = implode(',',$params['service']);
                    unset($params['images'],$params['coordinate']);
                    $result = \app\common\model\Shop::create($params);
                    //生成二维码
                    $qrcode_url = mkQrcodeCode(Env::get('app.app_host')."/member/apply?memberId=&shopId={$result->id}&type=1",md5(time().rand(1000,9999)),'uploads/shop_qrcode/');
                    $result->invite_qrcode = $qrcode_url;
                    $result->save();
                    $arr_info = [];
                    foreach ($images as $k => $v) {
                        $arr_info[$k]['shop_id'] = $result->id;
                        $arr_info[$k]['image_url'] = $v;
                        $arr_info[$k]['create_time'] = time();
                    }
                    Images::addImages($arr_info);
                    Message::create(['content'=>"代理添加了店铺:".$params['shop_name'].",请及时查看并审核！"]);
                    Db::commit();
                    $admins = Admin::where(['status'=>'normal','member_id'=>['gt',0]])->select();
                    foreach ($admins as $v){
                        Queue::push(\app\job\Message::class,[
                            'member_id'=>$v['member_id'],
                            'template_id'=>config('wechat_gzh')['gzh_template']['gd_wait_audit'],
                            'data'=>[
                                'thing13'=>"添加商家审核工单",
                                'phrase3'=> '代理商',
                                'time4'=>date('Y-m-d H:i')
                            ]
                        ],'message');
                    }
                }  catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            $service_ids = Service::field('id,name')->where(['status'=>1,'shop'=>1])->select()->toArray();
            $arr_ids = array_combine(array_column($service_ids, 'id'), array_column($service_ids, 'name'));
            $this->assign('serviceIds', $arr_ids);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     * @param null $ids
     * @return string
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids)->toArray();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $coordinate = explode(',',$params['coordinate']);
                $params['latitude'] =$coordinate[0];
                $params['longitude'] =$coordinate[1];
                $params = $this->preExcludeFields($params);
                if (empty($params['images'])) {
                    $this->model->clearImages($row['id']);
                } else {
                    $images = explode(',',$params['images']);
                    $result = Images::where(['shop_id'=>$ids])->delete();
                    if ($result !== false){
                        if (!empty($images)){
                            $arr_info = [];
                            foreach ($images as $k=>$v){
                                $arr_info[$k]['shop_id'] = $ids;
                                $arr_info[$k]['image_url'] = $v;
                                $arr_info[$k]['create_time'] = time();
                            }
                            Images::addImages($arr_info);
                        }
                    }
                }
                $result = false;
                Db::startTrans();
                try {
                    unset($params['images'],$params['coordinate']);
                    if (!empty($row['invite_qrcode'])){
                        if (file_exists(substr($row['invite_qrcode'],1)))
                            unlink(substr($row['invite_qrcode'],1));
                    }
                    $params['service'] = implode(',',$params['service']);
                    $qrcode_url = mkQrcodeCode(Env::get('app.app_host')."/member/apply?memberId=&shopId={$row['id']}&type=1",md5(time().rand(1000,9999)),'uploads/shop_qrcode/');
                    $params['invite_qrcode'] = $qrcode_url;
                    $params['audit_status'] = 0;
                    $result = $this->model->save($params,['id'=>$row['id']]);
                    Message::create(['content'=>"代理编辑了店铺:".$params['shop_name'].",请及时查看并审核！"]);
                    Db::commit();
                    $admins = Admin::where(['status'=>'normal','member_id'=>['gt',0]])->select();
                    foreach ($admins as $v){
                        Queue::push(\app\job\Message::class,[
                            'member_id'=>$v['member_id'],
                            'template_id'=>config('wechat_gzh')['gzh_template']['gd_wait_audit'],
                            'data'=>[
                                'thing13'=>"编辑商家审核工单",
                                'phrase3'=> '代理商',
                                'time4'=>date('Y-m-d H:i')
                            ]
                        ],'message');
                    }
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            $service_ids = Service::field('id,name')->where(['status'=>1,'shop'=>1])->select()->toArray();
            $arr_ids = array_combine(array_column($service_ids, 'id'), array_column($service_ids, 'name'));
            $this->assign('serviceIds', $arr_ids);
            $row['coordinate'] = $row['latitude'].','.$row['longitude'];
            $images = Images::where('shop_id',$ids)->column('image_url');
            $row['images'] = implode(',',$images);
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->where('agent_id',$this->agent_id)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $v->deletetime = time();
                    $v->is_del = 1;
                    $count += $v->save();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 详情
     */
    public function detail($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids,['amapProvince','amapCity','amapDistricts','shopImages']);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('info', $row);
        return $this->view->fetch();
    }

    /**
     * 店铺成员
     */
    public function member($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids,['amapProvince','amapCity','amapDistricts','shopImages']);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('info', $row);
        return $this->view->fetch();
    }




    /**
     * 上传文件
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload('uploads/shop/'.md5(time()));
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }

        $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
    }



}
